import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/product_provider.dart';
import '../../models/product.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';

class AddEditProductScreen extends StatefulWidget {
  final int restaurantId;
  final Product? product;

  const AddEditProductScreen({
    super.key,
    required this.restaurantId,
    this.product,
  });

  @override
  State<AddEditProductScreen> createState() => _AddEditProductScreenState();
}

class _AddEditProductScreenState extends State<AddEditProductScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _specController = TextEditingController();
  final _priceController = TextEditingController();

  bool _isSaving = false;

  @override
  void initState() {
    super.initState();
    // 如果是编辑模式，用已有数据填充表单
    if (widget.product != null) {
      _nameController.text = widget.product!.name;
      _specController.text = widget.product!.spec;
      _priceController.text = widget.product!.currentPrice.toString();
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _specController.dispose();
    _priceController.dispose();
    super.dispose();
  }

  Future<void> _saveProduct() async {
    if (!_formKey.currentState!.validate()) return;
    if (_isSaving) return;

    setState(() {
      _isSaving = true;
    });

    try {
      final productProvider = Provider.of<ProductProvider>(context, listen: false);
      final product = Product(
        id: widget.product?.id,
        restaurantId: widget.restaurantId,
        name: _nameController.text.trim(),
        spec: _specController.text.trim(),
        currentPrice: double.parse(_priceController.text),
      );

      bool success;
      if (widget.product == null) {
        success = await productProvider.addProduct(product);
      } else {
        success = await productProvider.updateProduct(product);
      }

      if (success) {
        SnackbarHelper.showSuccess(
          context, 
          widget.product == null ? '商品添加成功' : '商品信息已更新'
        );
        
        // 延迟返回让用户看到成功提示
        await Future.delayed(const Duration(milliseconds: 1500));
        Navigator.of(context).pop(true); // 返回true表示需要刷新
      } else {
        SnackbarHelper.showError(context, '保存失败，请重试');
      }
    } catch (e) {
      SnackbarHelper.showError(context, e.toString());
    } finally {
      setState(() {
        _isSaving = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.product == null ? '添加商品' : '编辑商品',
          style: AppTheme.titleLarge,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '商品名称*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入商品名称';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _specController,
                decoration: const InputDecoration(
                  labelText: '规格* (如: 箱、瓶、斤)',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入规格';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _priceController,
                decoration: const InputDecoration(
                  labelText: '单价*',
                  border: OutlineInputBorder(),
                  labelStyle: AppTheme.bodyMedium,
                ),
                style: AppTheme.bodyLarge,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入单价';
                  }
                  if (double.tryParse(value) == null) {
                    return '请输入有效的金额';
                  }
                  if (double.parse(value) <= 0) {
                    return '单价必须大于0';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              ElevatedButton(
                onPressed: _isSaving ? null : _saveProduct,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: _isSaving
                    ? const SizedBox(
                        height: 20,
                        width: 20,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text('保存', style: AppTheme.bodyLarge),
              ),
            ],
          ),
        ),
      ),
    );
  }
}